package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.oa.core.entity.com.OrderEntity;
import com.fz.us.oa.core.entity.com.OrderTrack;
import com.fz.us.oa.core.service.com.OrderEntityService;
import com.fz.us.oa.core.service.com.OrderTrackService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/20.
 */
@Controller
@RequestMapping(value = "/com/orderTrack")
public class OrderTrackController extends BaseController {
    private static final long serialVersionUID = 6250746827557059346L;

    @Autowired
    private OrderTrackService orderTrackService;
    @Autowired
    private OrderEntityService orderEntityService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private DutyService dutyService;

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String parentId,String draft,String index,String todo,String remind,String record) {
        if (StringUtils.isNotEmpty(keyId)){
            OrderTrack orderTrack=orderTrackService.get(keyId);
            OrderEntity orderEntity=orderTrack.getOrderEntity();
            model.addAttribute("keyId", keyId);
            model.addAttribute("orderTrack", orderTrack);
            model.addAttribute("orderEntity", orderEntity);
        }else{
            OrderEntity orderEntity=orderEntityService.get(parentId);
            model.addAttribute("orderEntity", orderEntity);
        }
        model.addAttribute("parentId", parentId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/orderTrack_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            OrderTrack orderTrack=orderTrackService.get(keyId);
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            String isEdit =  isEdit(keyId);
            model.addAttribute("isEdit", isEdit);
            model.addAttribute("orderTrack", orderTrack);
            model.addAttribute("stepNo", stepNo);
            model.addAttribute("rate",orderTrack.getRate()+"%");
        }
        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/orderTrack_read";
    }

    /**
     * 保存model操作
     */
    public OrderTrack saveModel(User user, String keyId, String parentId, String trackDate, Integer rate, String completion, Integer difficulty,
                                String difficultyText, Integer overcome) throws ParseException {
        OrderTrack orderTrack=null;
        if(StringUtils.isBlank(keyId)){
            orderTrack=new OrderTrack();
            orderTrack.setCreater(user);
            orderTrack.setCompany(user.getCompany());
            orderTrack.setName("biblee");
        }else{
            orderTrack=orderTrackService.get(keyId);
        }

        if(StringUtils.isNotEmpty(parentId)){
            orderTrack.setOrderEntity(orderEntityService.get(parentId));
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        if(StringUtils.isNotEmpty(trackDate)){
            orderTrack.setTrackDate(sdf.parse(trackDate));
        }
        if(rate!=0){
            orderTrack.setRate(rate);
        }
        if(StringUtils.isNotEmpty(completion)){
            orderTrack.setCompletion(completion);
        }
        if(difficulty!=null){
            orderTrack.setDifficulty(difficulty);
            if(difficulty==2){
                orderTrack.setDifficultyText(difficultyText);
                if(overcome!=null){
                    orderTrack.setOvercome(overcome);
                }
            }
        }

        return orderTrack;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,
                       @RequestParam(required = false) String keyId,
                       String parentId,
                       String trackDate,
                       Integer rate,
                       String completion,
                       Integer difficulty,
                       String difficultyText,
                       @RequestParam(required = false) Integer overcome) throws ParseException {

        Map<String,Object> rMap=new HashMap<String,Object>();
        OrderTrack orderTrack=saveModel(user,keyId,parentId,trackDate,rate,completion,difficulty,difficultyText,overcome);

        if(StringUtils.isNotEmpty(keyId)){
            orderTrackService.update(orderTrack);
            rMap.put("message", "更新成功");
        } else {
            orderTrackService.save(orderTrack, "com.fz.us.oa.core.entity.com.OrderTrack");
            rMap.put("message", "保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 提交操作
     */
    @RequestMapping(value = "submit", method = RequestMethod.POST)
    public Object submit(@CurrentUser User user,
                         @RequestParam(required = false) String keyId,
                         String parentId,
                         String trackDate,
                         Integer rate,
                         String completion,
                         int difficulty,
                         String difficultyText,
                         int overcome,
                         String curDutyId,
                         String comment) throws ParseException {

        Map<String, Object> rMap = new HashMap<String, Object>();
        OrderTrack orderTrack=saveModel(user,keyId,parentId,trackDate,rate,completion,difficulty,difficultyText,overcome);

        if (StringUtils.isNotEmpty(keyId)) {
            orderTrackService.approve(orderTrack, dutyService.get(curDutyId), comment);
        } else {
            orderTrackService.commit(orderTrack, "com.fz.us.oa.core.entity.com.OrderTrack", dutyService.get(curDutyId));
        }

        if(orderTrack.getProcessState().name().equals("Finished")){
            doFinished(orderTrack,parentId);
        }

        rMap.put("message", "提交成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment, String parentId){
        Map<String,Object> rMap=new HashMap<String,Object>();
        OrderTrack orderTrack=orderTrackService.get(keyId);
        orderTrackService.approve(orderTrack, dutyService.get(curDutyId), comment);

        //归档后...
        if(orderTrack.getProcessState().name().equals("Finished")){
            doFinished(orderTrack,parentId);
        }
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    public void doFinished(OrderTrack orderTrack,String parentId){
        OrderEntity orderEntity =orderEntityService.get(parentId);
        orderEntity.setRate(orderTrack.getRate());
        orderEntity.setTrackDate(orderTrack.getTrackDate());
        if(orderTrack.getDifficulty()==2&&orderTrack.getOvercome()==1){
            orderEntity.setRed(true);
        }
        orderEntityService.update(orderEntity);
    }

    /**
     * 进入list页面
     */
    @RequestMapping(value = "toList", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String toList(Model model,String parentId) {

        model.addAttribute("parentId", parentId);

        return "/main/menu/com/orderTrack";
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,Model model,
                                    String viewtype,
                                    JqGridPager pager,
                                    String parentId,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = null;

        SearchResultPaging searchResult = null;
        Map<String,Object> params = new HashMap<String,Object>();
        OrderEntity orderEntity=orderEntityService.get(parentId);
        params.put("company", company);
        params.put("state", BaseEnumManager.StateEnum.Enable);
        //当前订单的跟踪表
        params.put("orderEntity", orderEntity);
        searchResult = orderTrackService.paging(null,null,order,
                "com.fz.us.oa.core.entity.com.OrderTrack",
                new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Running}, params);


        List<OrderTrack> orderTrackList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(OrderTrack orderTrack: orderTrackList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",orderTrack.getId());
            rMap.put("trackDate", DataUtil.DateToString(orderTrack.getTrackDate()));
            rMap.put("rate", orderTrack.getRate()+"%");
            if(orderTrack.getDifficulty()==1){
                rMap.put("difficulty","否");
                rMap.put("overcome", "");
            }else{
                rMap.put("difficulty","是");
                if(orderTrack.getOvercome()==1){
                    rMap.put("overcome", "未克服");
                }else if(orderTrack.getOvercome()==2){
                    rMap.put("overcome", "已克服");
                }else{
                    rMap.put("overcome", "");
                }
            }
            rMap.put("creater", orderTrack.getCreater().getName());
            rMap.put("createTime", DataUtil.DateToString(orderTrack.getCreateTime()));
            dataRows.add(rMap);
        }
        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 克服障碍
     */
    @RequestMapping(value = "overcome", method = RequestMethod.POST)
    public Object saveOvercome(@CurrentUser User user, String keyId){
        OrderTrack orderTrack=orderTrackService.get(keyId);
        OrderEntity orderEntity=orderTrack.getOrderEntity();
        if(!user.getId().equals(orderTrack.getCreater().getId())){
            return ajaxJson(resultService.fail("您不是提交人"));
        }
        orderTrack.setOvercome(2);
        orderTrackService.saveEntity(orderTrack);
        if(orderTrackService.checkRed(orderEntity)){
            System.out.println("还有");
        }else{
            System.out.println("没了");
            orderEntity.setRed(false);
            orderEntityService.saveEntity(orderEntity);
        }
        return ajaxJson(resultService.success("克服障碍成功"));
    }

}
